<template>
  <el-dialog
    title="分配角色"
    :visible="isShow"
    @close="handleClose"
    @open="handleOpen"
  >
    <!-- 角色列表 {{ userId }} -->

    <!-- 多选框的玩法1: 记录的是 布尔值(选中还是不选中) -->
    <!-- <el-checkbox v-model="flag">是否单身</el-checkbox> -->

    <!-- 多选框的玩法2: 记录的是 哪些被选中了 数组 -->
    <!-- 将来收集到数组中的字段 是 label -->
    <el-checkbox-group v-model="checkedList" v-loading="loading">
      <el-checkbox
        v-for="item in roleList"
        :key="item.id"
        :label="item.id"
      >{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button size="small" @click="handleClose">取消</el-button>
      <el-button size="small" type="primary" @click="submit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqAssignRoles, reqGetRoleList } from '@/api/setting'
import { reqGetBaseInfo } from '@/api/user'
export default {
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      // flag: false,
      checkedList: [],
      roleList: [],
      loading: false
    }
  },
  methods: {
    handleOpen() {
      // 弹窗打开才触发
      this.loading = true // 开启loading
      // this.getRoleList() // 获取所有角色
      // this.getEmployeeDetail() // 获取用户之前的角色用于回显
      // console.log(1)
      // setTimeout(() => {
      //   console.log(2)
      // }, 1000)
      // console.log(3)
      // this.loading = false
      // 需求: 想等两个请求都结束了 再关闭loading
      // Promise.race / Promise.all([p1, p2, p3]).then(() => { .... })
      // 处理前端请求并发
      const p1 = this.getRoleList()
      const p2 = this.getEmployeeDetail()
      Promise.all([p1, p2]).then(() => {
        // ...
        this.loading = false
      })
    },
    handleClose() {
      this.$emit('update:isShow', false)
      this.checkedList = [] // 清空选中项
    },
    // async 函数 天然返回promise
    async getRoleList() {
      // 获取所有的角色
      const { data: { rows }} = await reqGetRoleList(1, 999999)
      // console.log(data)
      this.roleList = rows
      // this.loading = false
    },
    async getEmployeeDetail() {
      const { data: { roleIds }} = await reqGetBaseInfo(this.userId)
      // console.log(data)
      this.checkedList = roleIds
      // this.loading = false
    },
    async submit() {
      await reqAssignRoles(this.userId, this.checkedList)
      this.$message.success('分配角色成功')
      this.handleClose()
    }
  }
}
</script>

<style>

</style>
